import React, { useCallback, useEffect, useState } from "react";
import { Button, Toast, Modal } from "antd-mobile";
import { withRouter } from "react-router";
import initIO from '@/utils/socket'

import "./style.css";
import _http from "@/_http";

const alert = Modal.alert;

const Order = ({ match, history }) => {
  const [orders, setOrders] = useState([])
  const [openid, setOpenid] = useState(match.params.openid)
  const [store, setStore] = useState('1')
  const [payStatus, setPayStatus] = useState('1')

  useEffect(async () => {
    await getData()
    initIO(io => {
      io.socket.on('createOrderSuccess', async function (data) {
        console.log('客户端收到服务器发送的消息', data);
        await getData()
      })
    })
  }, [store, payStatus])

  const getData = useCallback(async () => {
    const res = openid ? await _http('/order/list?openid=' + openid) : await _http('/order/list', {
      store,
      status: payStatus
    })
    if (res.data.code === 1) {
      setOrders(res.data.data)
    } else {
      setOrders([])
    }
  }, [openid, store, payStatus])

  const showDetail = useCallback((id) => {
    history.push('/orderdetail/' + id)
  }, []);

  const updateFoodStatus = useCallback(async (id, status = 3) => {
    const res = await _http('/order/updateOrderStatus', { status, id }, 'POST')
    if (res.data.code === 1) {
      Toast.success(res.data.msg, 1);
    } else {
      Toast.fail(res.data.msg, 1);
    }
  }, []);


  return (
    <div className="order_wrapper">
      <div id="topAnchor"></div>
      <select value={store} onChange={(e) => { setStore(e.target.value); }} style={{ margin: '10px 0' }}>
        <option value="1">味好佳</option>
        <option value="2">左记</option>
      </select>
      <select value={payStatus} onChange={(e) => { setPayStatus(e.target.value); }} style={{ margin: '10px 0' }}>
        <option value="1">支付成功</option>
        <option value="2">待支付</option>
        <option value="3">支付失败</option>
      </select>
      {orders.map((order) => (
        <div className="o_item" key={order._id} onClick={() => showDetail(order.id)}>
          <div className="o_left">
            <div className="o_name">{order.name}</div>
            <div className="o_items">
              {order.foods.map((food) => (
                <div key={food._id}>{food.name + ` *` + food.count + "份"}</div>
              ))}
            </div>
            {order.remark ? <div className="if-item" style={{ color: 'rgb(255 79 79)' }}>
              <div className="if-label">备注：</div>
              <div className="if-value">{order.remark}</div>
            </div> : null}

          </div>
          <div className="o_right">
            {order.order_status && order.status == '1' ? order.order_status : '未支付'}
            <Button
              size="small"
              onClick={(e) => {
                e.stopPropagation()
                alert('提示', '确定已完成该订单吗?', [
                  { text: '取消', onPress: () => console.log('cancel') },
                  {
                    text: '确定',
                    onPress: () => {
                      updateFoodStatus(order.id, order.status)
                    }
                  },
                ])
              }}
            >
              制作完成
          </Button>
            <div className="o_price">￥{order.price / 100}</div>
          </div>
        </div>
      ))}
      <a href="#topAnchor">
        <div className="fixedbtn">
          <img src={require('@/icons/top.svg').default} alt="置顶" />
        </div>
      </a>
    </div>
  );
};

export default withRouter(Order);
